<?php
/**
 * 防止重复请求
 */

namespace app\common\behavior;

use think\facade\Cache;
use think\facade\Config;
use think\Controller;
use think\facade\Request;

class RepeatRequest extends Controller {
    
    /**
     * @desc 防止重复请求
     * @param int $uniqueID 唯一标识
     * @return bool|void
     * @throws \HttpResponseException
     */
    public function run($uniqueID = 0) {
        $key = md5(Request::path() . Request::getInput() . $uniqueID);
        $cachePrefix = Config::get('cache.default')['prefix'] . Config::get('cache_option.prefix')['repeat_request'];
        $cacheKey = $cachePrefix . $key;
        $cache = Cache::init();
        $redisHandler = $cache->handler();
        if (!$redisHandler->set($cacheKey, true, ['nx', 'ex' => Config::get('cache_option.expire')['repeat_request']])) {
            $data = ['errorCode' => EC_REPEAT_REQUEST, 'message' => Config::pull('errorcode')[EC_REPEAT_REQUEST]];
            return response_exception($data);
        }
        return true;
    }
}